﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
using USERS.CYT369.COM.Models;

namespace USERS.CYT369.COM.Controllers
{

    [SystemExceptionProcessor]
    public class BaseController : Controller
    {
        class UpperCaseNamingPolicy : System.Text.Json.JsonNamingPolicy
        {
            public override string ConvertName(string name)
            {
                return name;
            }
        }

        public static object s_lock_object = new object();
        private UserSession m_UserSession = null;

        public UserSession UserSession
        {
            get
            {
                if (m_UserSession == null)
                {
                    lock (s_lock_object)
                    {
                        if (m_UserSession == null)
                        {
                            m_UserSession = this.HttpContext.RequestServices.GetService(typeof(UserSession)) as UserSession;
                        }
                    }
                }

                return m_UserSession;
            }
        }

        public int GetUserId()
        {
            var item = this.User.Claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier).FirstOrDefault();
            int id = 0;
            if (item != null)
            {
                int.TryParse(item.Value, out id);
            }

            return id;
        }

        public ContentResult Content(bool b)
        {
            return base.Content(b.ToString().ToLower());
        }

        public JsonResult DefaultJson(object obj)
        {
            var setting = new System.Text.Json.JsonSerializerOptions()
            {
                PropertyNamingPolicy = new UpperCaseNamingPolicy()
            };


            return base.Json(obj, setting);
        }

        protected async Task<T> GetObject<T>() where T : class
        {
            int len = 0;
            var stream = new System.IO.MemoryStream();
            var buffer = new byte[1024];
            while ((len = await this.Request.Body.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                stream.Write(buffer, 0, len);
            }

            var json = System.Text.Encoding.UTF8.GetString(stream.ToArray());
            Console.WriteLine(json);
            var obj = System.Text.Json.JsonSerializer.Deserialize<T>(json);

            return obj;
        }

        public static string GetClientUserIp(Microsoft.AspNetCore.Http.HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            return ip;
        }

        #region 图片验证码
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public virtual IActionResult GetCaptcha(string userName)
        {
            try
            {
                int CaptchaLen = 4;
                int codeW = 80;
                int codeH = 25;
                int fontSize = 16; Random rnd = new Random();
                //颜色列表，用于验证码、噪线、噪点
                Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
                //字体列表，用于验证码
                string[] font = { "Times New Roman", "Goudy Stout", "Viner Hand ITC", "Georgia", "Arial", "Comic Sans MS" };
                //验证码的字符集，去掉了一些容易混淆的字符

                //写入Session、验证码加密
                //WebHelper.WriteSession("session_verifycode", Md5Helper.MD5(chkCode.ToLower(), 16));
                //创建画布
                var bmp = new Bitmap(codeW, codeH);
                var g = Graphics.FromImage(bmp);
                g.Clear(Color.White);
                //画噪线
                var lineNum = rnd.Next(5);
                for (int i = 0; i < lineNum; i++)
                {
                    int x1 = rnd.Next(codeW);
                    int y1 = rnd.Next(codeH);
                    int x2 = rnd.Next(codeW);
                    int y2 = rnd.Next(codeH);
                    Color clr = color[rnd.Next(color.Length)];
                    g.DrawLine(new Pen(clr), x1, y1, x2, y2);
                }
                //画验证码字符串
                string chkCode = "";
                for (int i = 0; i < CaptchaLen; i++)
                {
                    string fnt = font[rnd.Next(font.Length)];
                    Font ft = new Font(fnt, fontSize);
                    Color clr = color[rnd.Next(color.Length)];

                    var ch = "a";
                    switch (rnd.Next(0, 100) % 3)
                    {
                        case 0:
                            do
                            {
                                ch = ((char)rnd.Next('a', 'z')).ToString();
                            } while (ch == "o" || ch == "l" || ch == "z");
                            break;

                        case 1:
                            do
                            {
                                ch = ((char)rnd.Next('A', 'Z')).ToString();
                            } while (ch == "O" || ch == "I" || ch == "Z");
                            break;

                        default:
                            ch = ((char)rnd.Next('0', '9')).ToString();
                            break;
                    }

                    chkCode += ch;
                    g.DrawString(ch, ft, new SolidBrush(clr), (float)i * (18 + rnd.Next(2)), (float)rnd.Next(5));
                }

                //将验证码图片写入内存流，并将其以 "image/Png" 格式输出
                var ms = new System.IO.MemoryStream();
                try
                {
                    var image = TwistImage(bmp, true, Next(1, 3), Next(4, 6));

                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    //return ms.ToArray();
                    this.UserSession.ImageCaptchaCode = chkCode;
                    if (string.IsNullOrEmpty(userName))
                    {
                        userName = this.HttpContext.Session.Id;
                    }
                    CYT369.COM.DAL.RedisService.Instance.SetImageCaptcha(userName, chkCode);

                    return new FileStreamResult(ms, "image/png");
                }
                catch (Exception)
                {
                    return null;
                }
                finally
                {
                    g.Dispose();
                    bmp.Dispose();
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 正弦曲线Wave扭曲图片
        /// </summary>
        /// <param name="srcBmp">图片路径</param>
        /// <param name="bXDir">如果扭曲则选择为True</param>
        /// <param name="nMultValue">波形的幅度倍数，越大扭曲的程度越高,一般为3</param>
        /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
        private System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
        {
            double PI = 6.283185307179586476925286766559;
            Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
            Graphics graph = Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();
            double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
            for (int i = 0; i < destBmp.Width; i++)
            {
                for (int j = 0; j < destBmp.Height; j++)
                {
                    double dx = 0;
                    dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen;
                    dx += dPhase;
                    double dy = Math.Sin(dx);
                    int nOldX = 0, nOldY = 0;
                    nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
                    nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                    Color color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }
            srcBmp.Dispose();
            return destBmp;
        }

        /// <summary>
        /// 获得下一个随机数
        /// </summary>
        /// <param name="min">最小值</param>
        /// <param name="max">最大值</param>
        private int Next(int min, int max)
        {
            int value = Next2(max - min) + min;
            return value;
        }

        /// <summary>
        /// 获得下一个随机数
        /// </summary>
        /// <param name="max">最大值</param>
        private int Next2(int max)
        {
            var rand = new System.Security.Cryptography.RNGCryptoServiceProvider();
            byte[] randb = new byte[4];
            rand.GetBytes(randb);
            int value = BitConverter.ToInt32(randb, 0);
            value = value % (max + 1);
            if (value < 0) value = -value;
            return value;
        }
        #endregion

        #region 手机验证码
        protected bool GetMobileCaptcha(string phoneNumber, ref string errMsg)
        {
            if (string.IsNullOrEmpty(phoneNumber))
            {
                errMsg = "手机号不能为空";
            }
            else
            {
                var captchCode = USERS.CYT369.COM.Models.LoginHelper.MakeCaptchaCode();
                var success = USERS.CYT369.COM.Models.LoginHelper.SendCaptcha(phoneNumber, captchCode);
                if (success)
                {
                    this.UserSession.PhoneNumber = phoneNumber;
                    CYT369.COM.DAL.RedisService.Instance.SetMobileCaptcha(phoneNumber, captchCode);
                    return true;
                }
                else
                {
                    errMsg = "获取验证码失败";
                }
            }

            return false;
        }

        #endregion
    }

    public class AllowAnonymousController : BaseController
    {
    }

    [Authorize]
    public class AuthorizeController : BaseController
    {

    }
}
